import { api } from '../../utils/api';

Page({
  data: {
    contacts: [] as any[],
    loading: false,
    pendingCount: 0, // 待处理的好友请求数量
  },

  onLoad() {
    this.loadContacts();
  },

  onShow() {
    this.loadContacts();
    this.loadPendingCount();
  },

  async loadContacts() {
    this.setData({
      loading: true,
    });

    try {
      const res: any = await api.getContacts();
      if (res.success && res.contacts) {
        // 后端已经返回了用户的详细信息（nickname、avatar等）
        this.setData({
          contacts: res.contacts,
        });
      }
    } catch (error) {
      console.error('加载通讯录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
    } finally {
      this.setData({
        loading: false,
      });
    }
  },

  onContactTap(e: any) {
    const contactId = e.currentTarget.dataset.contactid;
    wx.navigateTo({
      url: `/pages/contact-detail/contact-detail?contactId=${contactId}`,
    });
  },

  onAddContactTap() {
    // 跳转到"新的朋友"页面，显示待处理的好友请求
    wx.navigateTo({
      url: '/pages/new-friends/new-friends',
    });
  },

  async loadPendingCount() {
    try {
      const res: any = await api.getPendingRequests();
      if (res.success && res.requests) {
        this.setData({
          pendingCount: res.requests.length,
        });
      }
    } catch (error) {
      console.error('加载待处理请求数量失败:', error);
    }
  },
});

